﻿using Framework.Caching.Monitors;
using Framework.Common.LogOperation;
using Framework.Common.SerializeOperation;
using Framework.Data.EF;
using Framework.Redis;
using PaPaPa.Data.Monitors;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace PaPaPa.Data.EF
{
    public class DataWrapper<T> : EFWrapperBase<T>
        where T : class,new()
    {
        public DataWrapper()
        {
            base.Context.EventRegistModel += ModelRegister.Regist;
        }

        public override async Task<int> SaveAsync()
        {
            var result = await base.SaveAsync();

            SaveToRedis();

            return result;
        }

        private void SaveToRedis()
        {
            try
            {
                var type = typeof(T);
                var monitor = EqualsMonitorManager<string, RedisCacheMonitor>.Get(MonitorConstant.REDIS_KEY, x => x.TableName == type.Name);
                if (monitor != null)
                {
                    foreach (var entity in base.DbSet.Local)
                    {
                        foreach (var field in monitor.Fields)
                        {
                            var pi = type.GetProperty(field);
                            RedisSingleton.GetInstance.Client.HSet(type.Name, string.Format("{0}:{1}", pi.Name, pi.GetValue(entity, null).ToString()), entity);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex.ToString());
            }
        }

    }
}
